package com.offices.subscribe.controller;


import com.offices.subscribe.services.MessageService;
import com.offices.subscribe.utils.HttpRequestMethod;
import com.offices.subscribe.services.WxService;
import com.offices.subscribe.utils.AccessTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping(value = "/wx")
public class NgrokController {

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    @RequestMapping(value = "/checked",method = RequestMethod.GET)
    public String ngrokTest(HttpServletRequest request){
        System.out.println("checked");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        if (WxService.check(timestamp, nonce, signature)) {
            System.out.println("接入成功");
            return echostr;

        } else {
            System.out.println("接入失败");
        }
        return "hello";
    }

    @RequestMapping(value = "/checked",method = RequestMethod.POST)
    public String getMessage(HttpServletRequest request) throws IOException {
        //添加解码参数
        request.setCharacterEncoding(HttpRequestMethod.UTF8_ENCODE.getMethod());
        //将请求信息封装为map数据
        Map<String, String> requestMap = WxService.parseRequest(request.getInputStream());
        System.out.println(requestMap);
        //String response = "<xml><ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName><FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName><CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime><MsgType><![CDATA[text]]>></MsgType><Content><![CDATA[你好!!!!!]]></Content></xml>";
        //填充回复信息
        //String response = "<xml>\n" +
        //        "  <ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName>\n" +
        //        "  <FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName>\n" +
        //        "  <CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime>\n" +
        //        "  <MsgType><![CDATA[text]]></MsgType>\n" +
        //        "  <Content><![CDATA[你好!!!!!]]></Content>\n" +
        //        "</xml>";
        //处理发来的信息
        String result = MessageService.handleMessage(requestMap);
        return result;
    }

    @RequestMapping(value = "/token",method = RequestMethod.GET)
    public void testToken() {
        accessTokenUtil.getAccessToken();
    }

}
